<?php

namespace app\webapi\controller;

use think\facade\Db;
use think\facade\Request;

class ApiUserIncome extends ApiBaseController
{
    public $user_info = null;

    public function __construct()
    {
        $this->user_info = $this->checkToken();
        if (!preg_match('/^\d+$/', $this->user_info['id'])) {
            $this->result_error('用户id出错');
        }
    }

    /**
     * 获取总收益统计信息
     */
    public function getIncomeInfo()
    {
        $sql_result = Db::name('user_income')->where('id', $this->user_info['id'])->find();
        if (empty($sql_result)) {
            $ins_result = Db::name('user_income')->insertGetId(['id' => $this->user_info['id']]);
            $sql_result = Db::name('user_income')->where('id', $this->user_info['id'])->find();
        }
        $data = $sql_result;
        $days7list = Db::query("SELECT SUM(income) income FROM sy_user_income_record WHERE uid=? AND DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= DATE(create_time)", [$this->user_info['id']]);
        $todaylist = Db::query("SELECT SUM(income) income FROM sy_user_income_record WHERE uid=? AND TO_DAYS(create_time) = TO_DAYS(NOW())", [$this->user_info['id']]);
        $data['days7'] = (float)($days7list[0]['income'] == null ? 0 : $days7list[0]['income']);
        $data['today'] = (float)($todaylist[0]['income'] == null ? 0 : $todaylist[0]['income']);
        $this->result_ok('ok', $data);
    }

    /**
     *获取佣金（已到账）
     */
    public function getIncomeRecord()
    {

        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        if ($page_size < 1) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index * $page_size;
        $sql = "SELECT a.*,b.avatar fans_avatar,b.nickname fans_nickname 
                FROM sy_user_income_record a 
                LEFT JOIN sy_user b ON a.fans_uid=b.id 
                WHERE a.uid=? 
                ORDER BY a.create_time DESC 
                LIMIT ?,?";
        $sql_count = "SELECT COUNT(*) total_count FROM sy_user_income_record WHERE uid=? ";
        $sql_result = Db::query($sql, [$this->user_info['id'], $limit, $page_size]);
        $sql_count_result = Db::query($sql_count, [$this->user_info['id']]);
        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result[0]['total_count'] ?? 0,
            'list' => $sql_result
        );
        $this->result_ok('ok', $data);

    }

    /**
     *获取佣金(未到账)
     */
    public function getIncomeRecordNotSure()
    {
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        if ($page_size < 1) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index * $page_size;
        $sql = "SELECT a.*,b.avatar fans_avatar,b.nickname fans_nickname,b.level1_recommender,b.level2_recommender  
                FROM sy_user_order a 
                INNER JOIN sy_user b ON a.uid=b.id 
                WHERE (b.level1_recommender=? OR b.level2_recommender=?) AND a.state=1 AND a.pay_state=0   
                ORDER BY a.create_time DESC 
                LIMIT ?,?";
        $sql_count = "SELECT COUNT(*) total_count  
                        FROM sy_user_order a 
                        INNER JOIN sy_user b ON a.uid=b.id 
                        WHERE (b.level1_recommender=? OR b.level2_recommender=?) AND a.state=1 AND a.pay_state=0";
        $sql_result = Db::query($sql, [$this->user_info['id'], $this->user_info['id'], $limit, $page_size]);
        $sql_count_result = Db::query($sql_count, [$this->user_info['id'], $this->user_info['id']]);

        //获取收益率
        $rates = Db::name('other_config')->whereIn('id', '2,3')->select()->toArray();
        $r1 = 0;
        $r2 = 0;
        foreach ($rates as $v) {
            if ($v['id'] == 2) {
                $r1 = (int)$v['value3'];
            } elseif ($v['id'] == 3) {
                $r2 = (int)$v['value3'];
            }
        }
        $total_income = 0;
        if (!empty($sql_result)) {
            foreach ($sql_result as &$v) {
                if ($v['level1_recommender'] == $this->user_info['id']) {
                    $v['income'] = $temp = (int)($v['g_price'] * $r1 * 0.001);
                } elseif ($v['level2_recommender'] == $this->user_info['id']) {
                    $v['income'] = $temp = (int)($v['g_price'] * $r2 * 0.001);
                }
                $total_income += $temp;
            }
        }

        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result[0]['total_count'] ?? 0,
            'list' => $sql_result ?? [],
            'total_income' => $total_income
        );
        $this->result_ok('ok', $data);
    }

    /**
     *申请提现
     */
    public function withDrawal()
    {
        $amount = (int)Request::param('amount');
        if (!($amount > 0)) {
            $this->result_error('提现金额不合法');
        }
        $sql_result = Db::name('user_income')->where('id', $this->user_info['id'])->find();
        Db::startTrans();
        try {
            if (empty($sql_result)) {
                $result = Db::name('user_income')->insertGetId(['id' => $this->user_info['id']]);
                if (!$result) {
                    throw new \Exception('插入数据失败!');
                }
                Db::commit();
                $this->result_error("没有可提现的余额");
            } else {
                $data = $sql_result;
                if ($data['income'] < $amount) {
                    $this->result_error("可提现余额不足");
                }
                $up_res = Db::name('user_income')->where('id', $this->user_info['id'])->dec('income', $amount)->update();;
                $ins_res = Db::name('user_withdrawal')->insertGetId([
                    'uid' => $this->user_info['id'],
                    'before_total_income' => $data['income_total'],
                    'before_availble_income' => $data['income'],
                    'amount' => $amount
                ]);
                if (!$up_res || !$ins_res) {
                    throw new \Exception('插入数据失败!');
                }
                Db::commit();
                $this->result_ok("申请成功");
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result_error("申请失败");
        }
    }

    /**
     *获取提现记录
     */
    public function getWithdrawalRecord()
    {
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
        if ($page_size < 1) {
            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
        }
        $limit = $page_index * $page_size;
        $sql = "SELECT * FROM sy_user_withdrawal WHERE uid=? ORDER BY verify_time DESC LIMIT ?,?";
        $sql_count = "SELECT COUNT(*) total_count FROM sy_user_withdrawal WHERE uid=? ";
        $sql_result = Db::query($sql, [$this->user_info['id'], $limit, $page_size]);
        $sql_count_result = Db::query($sql_count, [$this->user_info['id']]);
        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result[0]['total_count'] ?? 0,
            'list' => $sql_result[0] ?? []
        );
        $this->result_ok('ok', $data);
    }

    /**
     *获取收益信息（订单差价）
     */
    public function getOrderSaleIncomeInfo()
    {
        $page_size = (int)Request::param('page_size');
        $data = [
            'total' => 0,
            'today' => 0
        ];
        $todaylist = Db::query("SELECT SUM((newprice-oldprice)-payprice) today FROM sy_user_order_publish WHERE uid=? AND hassale=1 AND pay_state=1 AND TO_DAYS(update_time) = TO_DAYS(NOW())", [$this->user_info['id']]);
        $totallist = Db::query("SELECT SUM((newprice-oldprice)-payprice) total FROM sy_user_order_publish WHERE uid=? AND hassale=1 AND pay_state=1 ", [$this->user_info['id']]);
        $data['today'] = empty($todaylist[0]['today']) ? 0 : $todaylist[0]['today'];
        $data['total'] = empty($totallist[0]['total']) ? 0 : $totallist[0]['total'];
        $this->result_ok('ok', $data);
    }

    /**
     *获取收益列表（订单差价）
     */
    public function getOrderSaleIncome()
    {
        $page_size = (int)Request::param('page_size');
        $page_index = (int)Request::param('page_index');
//        if ($page_size < 1 ) {
//            $this->result_error("分页参数错误", ['page_index' => $page_index, 'page_size' => $page_size]);
//        }
        $limit = $page_index * $page_size;
        $sql = "SELECT a.*,b.name,b.img,c.order_no  
                FROM sy_user_order_publish a 
                LEFT JOIN sy_goods_rush b ON a.gid=b.id 
                LEFT JOIN sy_user_order c ON a.relate_order_id=c.id 
                WHERE a.uid=? AND a.pay_state=1 AND a.hassale=1  
                LIMIT ?,?";
        $sql_count = "SELECT COUNT(*) total_count FROM sy_user_order_publish WHERE uid=? AND pay_state=1 AND hassale=1";
        $sql_result = Db::query($sql, [$this->user_info['id'], $limit, $page_size]);
        $sql_count_result = Db::query($sql_count, [$this->user_info['id']]);

        $data = array(
            'page_index' => $page_index,
            'page_size' => $page_size,
            'total_count' => $sql_count_result[0]['total_count'] ?? 0,
            'list' => $sql_result[0] ?? []
        );
        $this->result_ok('ok', $data);
    }


}